﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;

namespace BW.Mes.WinForms.BasicData
{
    public partial class CustomerForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient = new HttpClient();
        private readonly string _apiBaseUrl = "https://localhost:7274";
        public CustomerForm()
        {
            InitializeComponent();
            
            // 绑定按钮事件
            btnAdd.Click += btnAdd_Click;
            btnEdit.Click += btnEdit_Click;
            btnDelete.Click += btnDelete_Click;
            btnRefresh.Click += btnRefresh_Click;
            btnQuery.Click += btnQuery_Click;

            this.Load += (s, e) => LoadCustomerData();
            this.Shown += CustomerForm_Shown;
            gridView1.CustomUnboundColumnData += gridView1_CustomUnboundColumnData;
        }

        private void SetupGridActionColumn()
        {
            var actionColumn = new DevExpress.XtraGrid.Columns.GridColumn();
            actionColumn.Caption = "操作";
            actionColumn.Name = "ActionColumn";
            actionColumn.Visible = true;
            actionColumn.VisibleIndex = 10;
            actionColumn.Width = 180;
            actionColumn.MinWidth = 180;
            actionColumn.ColumnEdit = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
            var buttonEdit = actionColumn.ColumnEdit as DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit;
            buttonEdit.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
            buttonEdit.Buttons.Clear();
            var editButton = new DevExpress.XtraEditors.Controls.EditorButton { Caption = "修改", Width = 60 };
            buttonEdit.Buttons.Add(editButton);
            var deleteButton = new DevExpress.XtraEditors.Controls.EditorButton { Caption = "删除", Width = 60 };
            buttonEdit.Buttons.Add(deleteButton);
            buttonEdit.ButtonClick += ButtonEdit_ButtonClick;
            gridView1.Columns.Add(actionColumn);
        }

        private void ButtonEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var rowHandle = gridView1.FocusedRowHandle;
            if (rowHandle >= 0)
            {
                var customer = gridView1.GetRow(rowHandle) as CustomerModel;
                if (customer != null)
                {
                    if (e.Button.Caption == "修改")
                    {
                        var updateForm = new UpdateCustomerForm(customer);
                        if (updateForm.ShowDialog() == DialogResult.OK)
                        {
                            LoadCustomerData();
                        }
                    }
                    else if (e.Button.Caption == "删除")
                    {
                        var confirm = XtraMessageBox.Show($"确定要删除客户 '{customer.CustomerName}' 吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (confirm == DialogResult.Yes)
                        {
                            DeleteCustomer(customer.Id);
                        }
                    }
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            var addForm = new AddCustomerForm();
            if (addForm.ShowDialog() == DialogResult.OK)
            {
                LoadCustomerData();
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length != 1)
            {
                XtraMessageBox.Show("请只选择一条要修改的数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var customer = gridView1.GetRow(selectedRows[0]) as CustomerModel;
            if (customer == null)
            {
                XtraMessageBox.Show("未获取到客户信息！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var updateForm = new UpdateCustomerForm(customer);
            if (updateForm.ShowDialog() == DialogResult.OK)
            {
                LoadCustomerData();
            }
        }

        private async void btnDelete_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length == 0)
            {
                XtraMessageBox.Show("请先选择要删除的客户！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var confirm = XtraMessageBox.Show($"确定要删除选中的 {selectedRows.Length} 个客户吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirm != DialogResult.Yes) return;
            foreach (var rowHandle in selectedRows)
            {
                var customer = gridView1.GetRow(rowHandle) as CustomerModel;
                if (customer != null)
                {
                    await DeleteCustomer(customer.Id);
                }
            }
            LoadCustomerData();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadCustomerData();
        }

        private async void LoadCustomerData()
        {
            try
            {
                var response = await _httpClient.GetAsync($"{_apiBaseUrl}/api/Customer/GetCustomer");
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<CustomerListResponse>(json);
                    gridControl1.DataSource = result.pageDatas;
                    gridView1.PopulateColumns();
                    gridView1.BestFitColumns();
                    gridView1.OptionsSelection.MultiSelect = true;
                    gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;
                    if (gridView1.Columns.Count > 0)
                        gridView1.Columns[0].VisibleIndex = 0;
                    EnsureSerialNumberColumn();
                    AfterBindCustomerData();
                }
                else
                {
                    XtraMessageBox.Show("获取客户数据失败！");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async Task DeleteCustomer(long id)
        {
            try
            {
                var response = await _httpClient.PutAsync($"{_apiBaseUrl}/api/Customer/DeleteCustomer?id={id}", null);
                if (!response.IsSuccessStatusCode)
                {
                    XtraMessageBox.Show("删除失败！");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"删除异常: {ex.Message}");
            }
        }

        private void EnsureSerialNumberColumn()
        {
            if (gridView1.Columns["序号"] == null)
            {
                var col = gridView1.Columns.AddField("序号");
                col.Caption = "序号";
                col.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
                col.Visible = true;
                col.VisibleIndex = 0;
            }
            else
            {
                gridView1.Columns["序号"].Visible = true;
                gridView1.Columns["序号"].VisibleIndex = 0;
            }
        }

        private void AfterBindCustomerData()
        {
            EnsureSerialNumberColumn();
            var idColumn = gridView1.Columns["Id"];
            if (idColumn != null) idColumn.Visible = false;
        }

        private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "序号" && e.IsGetData)
            {
                e.Value = e.ListSourceRowIndex + 1;
            }
        }

        private void CustomerForm_Shown(object sender, EventArgs e)
        {
            // 确保按钮在表单显示时可见（理论上不再需要 EnsureButtonsVisible）
            // EnsureButtonsVisible();
            // 测试按钮是否正确添加
            // TestButtonsVisibility();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            // TODO: Implement query logic here
            LoadCustomerData();
        }

        public class CustomerModel
        {
           
            public long Id { get; set; }
            [DisplayName("客户编码")]
            public string CustomerCode { get; set; }
            [DisplayName("客户名称")]
            public string CustomerName { get; set; }
            [DisplayName("客户简称")]
            public string Abbreviation { get; set; }
            [DisplayName("客户电话")]
            public string Phone { get; set; }
            [DisplayName("客户地址")]
            public string Address { get; set; }
            [DisplayName("统一社会信用代码")]
            public string USCC { get; set; }
            [DisplayName("客户描述")]
            public string CustomerMsg { get; set; }
            [DisplayName("创建人")]
            public string CreatedBy { get; set; }
            [DisplayName("创建时间")]
            public DateTime CreatedAt { get; set; } = DateTime.Now;
            [DisplayName("修改时间")]
            public DateTime? UpdatedAt { get; set; }
        }
        public class CustomerListResponse
        {
            public int totalCount { get; set; }
            public List<CustomerModel> pageDatas { get; set; }
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }
    }
}